/*
 * Copyright 2003-2005 (c) Live Media Pty Ltd. <argot@einet.com.au> 
 *
 * This software is licensed under the Argot Public License 
 * which may be found in the file LICENSE distributed 
 * with this software.
 *
 * More information about this license can be found at
 * http://www.einet.com.au/License
 * 
 * The Developer of this software is Live Media Pty Ltd,
 * PO Box 4591, Melbourne 3001, Australia.  The license is subject 
 * to the law of Victoria, Australia, and subject to exclusive 
 * jurisdiction of the Victorian courts.
 */

using System;

using TwoWayHashMap = argot.util.TwoWayHashMap;

using TypeElement = argot.TypeElement;
using TypeException = argot.TypeException;
using TypeInputStream = argot.TypeInputStream;
using TypeOutputStream = argot.TypeOutputStream;
using TypeReader = argot.TypeReader;
using TypeWriter = argot.TypeWriter;
namespace argot.meta
{
	
	public class MetaAbstract
	:MetaBase, TypeReader, TypeWriter, MetaExpression, MetaDefinition
	{

		public const System.String TYPENAME = "meta.abstract";
		
		private TwoWayHashMap _concreteToMap;
		
		public MetaAbstract()
		{
			_concreteToMap = new TwoWayHashMap();
		}

		override public System.String TypeName
		{
			get
			{
				return TYPENAME;
			}
			
		}

		public virtual void  AddMap(int concreteType, int mapType)
		{
			_concreteToMap.Add( concreteType, mapType );
		}
		
		public virtual System.Object Read(TypeInputStream inStream, TypeElement element)
		{
			return new MetaAbstract();
		}
		
		public virtual void Write(TypeOutputStream outStream, System.Object o, TypeElement element)
		{
		}
		
		public virtual void DoWrite(TypeOutputStream outStream, System.Object o)
		{
			int id = outStream.TypeMap.Library.GetId(o.GetType());
			int mapId = _concreteToMap.FindValue(id);
			if (mapId == -1)
			{
				throw new TypeException("can't write abstract type directly.:" + o.GetType().FullName);
			}
			outStream.WriteObject("u16", (System.Object) outStream.TypeMap.GetId(mapId));
			
			// This will force the mapId to be mapped in dynamic type maps.
			outStream.TypeMap.GetId(mapId);
			outStream.WriteObject(outStream.TypeMap.GetId(id), o);
		}
		
		public virtual System.Object DoRead(TypeInputStream inStream)
		{
			System.UInt16 type = (System.UInt16) inStream.ReadObject("u16");
			int mapId = inStream.TypeMap.GetSystemId(type);

			int concrete = _concreteToMap.FindKey(mapId);
			if (concrete == -1)
			{
				throw new TypeException("type not mapped:" + type + " " + inStream.TypeMap.GetName(type));
			}
			return inStream.ReadObject(inStream.TypeMap.GetId(concrete));
		}
		
		public virtual bool IsMapped(int id)
		{
			return _concreteToMap.FindValue(id) == -1?false:true;
		}
	}
}